package main

import (
	"github.com/j2go/apijson/db"
	"github.com/j2go/apijson/handler"
	"github.com/j2go/apijson/logger"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	setEnvIfExistsFile()
	db.Init()
	http.HandleFunc("/head", handler.HeadHandler)
	http.HandleFunc("/get", handler.GetHandler)
	http.HandleFunc("/post", handler.PostHandler)
	http.HandleFunc("/put", handler.PutHandler)
	http.HandleFunc("/delete", handler.DeleteHandler)

	addr := ":" + os.Getenv("port")
	logger.SetLevel(logger.DEBUG)
	logger.Info("server listen on " + addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Fatal(err)
	}
}

func setEnvIfExistsFile() {
	if bytes, err := os.ReadFile(".env"); err == nil {
		kvs := strings.Split(string(bytes), "\n")
		for _, kv := range kvs {
			if kv != "" {
				kv := strings.Split(kv, "=")
				os.Setenv(kv[0], kv[1])
				logger.Debug("set env: " + kv[0] + "=" + kv[1])
			}
		}
	}
}
